import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Box,
  Typography,
  Button,
  TableContainer,
  Table,
  TableHead,
  TableRow,
  TableCell,
  TableBody,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Tooltip,
} from '@mui/material';

export interface DataTableDialogProps {
  open: boolean;
  onClose: () => void;
  data: any[] | null;
  columns: string[] | null;
  title: string;
  pageSize?: number;
  onPageSizeChange?: (newPageSize: number) => void;
}

const DataTableDialog: React.FC<DataTableDialogProps> = ({
  open,
  onClose,
  data,
  columns,
  title,
  pageSize = 10,
  onPageSizeChange,
}) => {
  const [page, setPage] = useState(0);

  // 打开或pageSize变化时重置页码
  useEffect(() => {
    setPage(0);
  }, [open, pageSize]);

  // 无数据时渲染空状态
  if (!data || !columns) {
    return (
      <Dialog open={open} onClose={onClose} maxWidth="lg" fullWidth>
        <DialogTitle>{title}</DialogTitle>
        <DialogContent>
          <Box sx={{ p: 2, textAlign: 'center' }}>
            <Typography>没有可显示的数据</Typography>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={onClose} color="primary">
            关闭
          </Button>
        </DialogActions>
      </Dialog>
    );
  }

  // 分页计算
  const startIndex = page * pageSize;
  const endIndex = Math.min(startIndex + pageSize, data.length);
  const paginatedData = data.slice(startIndex, startIndex + pageSize);

  return (
    <Dialog open={open} onClose={onClose} maxWidth="lg" fullWidth>
      <DialogTitle>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, overflow: 'hidden' }}>
          <Tooltip title={title} placement="top" arrow>
            <Typography
              noWrap
              sx={{ maxWidth: 400, fontWeight: 'bold', overflow: 'hidden', textOverflow: 'ellipsis' }}
              component="span"
            >
              {title}
            </Typography>
          </Tooltip>
          <Tooltip title={`共${data.length}条，当前${startIndex + 1}-${endIndex}`} placement="top" arrow>
            <Typography
              variant="subtitle2"
              color="text.secondary"
              noWrap
              sx={{ maxWidth: 250, overflow: 'hidden', textOverflow: 'ellipsis' }}
              component="span"
            >
              （共{data.length}条，当前{startIndex + 1}-{endIndex}）
            </Typography>
          </Tooltip>
        </Box>
      </DialogTitle>
      <DialogContent>
        <Box sx={{ width: '100%' }}>
          <TableContainer>
            <Table stickyHeader size="small">
              <TableHead>
                <TableRow>
                  {columns.map((col, idx) => (
                    <TableCell key={idx} sx={{ fontWeight: 'bold', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 200 }}>
                      <Tooltip title={col} placement="top" arrow>
                        <span style={{ display: 'inline-block', maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', verticalAlign: 'middle', whiteSpace: 'nowrap' }}>{col}</span>
                      </Tooltip>
                    </TableCell>
                  ))}
                </TableRow>
              </TableHead>
              <TableBody>
                {paginatedData.map((row, ridx) => (
                  <TableRow key={ridx} hover>
                    {columns.map((col, cidx) => (
                      <TableCell key={cidx} sx={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 200 }}>
                        <Tooltip title={row[col] !== undefined ? String(row[col]) : ''} placement="top" arrow>
                          <span style={{ display: 'inline-block', maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', verticalAlign: 'middle', whiteSpace: 'nowrap' }}>
                            {row[col] !== undefined ? String(row[col]) : ''}
                          </span>
                        </Tooltip>
                      </TableCell>
                    ))}
                  </TableRow>
                ))}
                {paginatedData.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={columns.length} align="center">
                      没有数据
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </TableContainer>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mt: 2 }}>
            <FormControl size="small">
              <InputLabel id="rows-per-page-label">每页行数</InputLabel>
              <Select
                labelId="rows-per-page-label"
                value={pageSize}
                label="每页行数"
                onChange={(e) => onPageSizeChange?.(Number(e.target.value))}
              >
                {[5,10,20,50,100].map(size => (
                  <MenuItem key={size} value={size}>{size}</MenuItem>
                ))}
              </Select>
            </FormControl>
            <Box>
              <Button disabled={page === 0} onClick={() => setPage(page - 1)}>上一页</Button>
              <Typography component="span" sx={{ mx: 2 }}>
                第 {page + 1} 页（共 {Math.ceil(data.length / pageSize)} 页）
              </Typography>
              <Button disabled={endIndex >= data.length} onClick={() => setPage(page + 1)}>下一页</Button>
            </Box>
          </Box>
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} color="primary">关闭</Button>
      </DialogActions>
    </Dialog>
  );
};

export default DataTableDialog;
